package helpers;

import java.util.concurrent.ConcurrentHashMap;

public class LocationCalculator {
	private String tag;
	private ConcurrentHashMap<String, String> readers;
	private long startTime; // time the first distance was added

	private static ConcurrentHashMap<String, LocationCalculator> calcs = new ConcurrentHashMap<>();
	
	public LocationCalculator(String tag) {
		super();
		this.tag = tag;
		this.readers = new ConcurrentHashMap<>();
	}

	public void addDistance(String reader, Float distance, Float readerX, Float readerY){
		if (readers.size() == 0)
			this.startTime = System.nanoTime();   
			
		readers.put(reader, readerX+","+readerY+","+distance.toString());

		long elapsedTime = System.nanoTime() - startTime;   
		
		if (readers.size() >= 3 && (elapsedTime / 1000000000) >= 2){ // && (elapsedTime / 100000000) <= 15
			//TODO: dispatch to location estimator in Mathematica
			MathLink.getLinkInstance().EstimateLocation(readers, tag);
			readers.clear();
		} else if ((elapsedTime / 1000000000) >= 2)
			readers.clear();
	}
	
	public static LocationCalculator getCalc(String tag){
		if (!calcs.containsKey(tag)) 
			calcs.put(tag, new LocationCalculator(tag));
		
		return calcs.get(tag);
	}
}
